﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MedicalAdviser.DataTypes.WsTypes;
using dts = MedicalAdviser.DataTypes;
using JsnUtils = Newtonsoft;

namespace MedicalAdviser.HtppProxy.HttpOperations
{
    public class Operations
    {



        //public static T Get<T,I>(String baseUrl, String operation , I inParameter)
        //{
        //    HttpClient client = new HttpClient();
        //    client.BaseAddress = new Uri(baseUrl);

        //    client.DefaultRequestHeaders.Accept.Add(
        //            new MediaTypeWithQualityHeaderValue("application/json"));

        //}



        /// <summary>
        /// This method call a http webservice, and accept generic parameters
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="I"></typeparam>
        /// <param name="baseUrl"></param>
        /// <param name="operation"></param>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public static T Post<T,I>(String baseUrl, String operation , I parameter  )
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(baseUrl);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

            var formatters = new List<MediaTypeFormatter>()
            {
                new JsonMediaTypeFormatter(),
                new XmlMediaTypeFormatter()
            };

            String operationUrl = String.Format("{0}/{1}", baseUrl, operation);
            var response = client.PostAsJsonAsync(operationUrl, parameter).Result;

            if (response.IsSuccessStatusCode)
            {

                String tmp = response.Content.ReadAsStringAsync().Result;
                /* Se houve uma comunicação bem sucedida com o webservice vou seriazilar a resposta para o tipo da respota */    
                return JsnUtils.Json.JsonConvert.DeserializeObject<T>(tmp);
            }
            else
            {
                var st = MethodBase.GetCurrentMethod().Name;
                

                throw  new Exception( 
                            String.Format( "Error when try to connect service on adress {0} on opertion {1}",baseUrl,operation),    
                            new Exception( String.Format("Exeption thorw on method {0}" , st) )
                    );
            }
        }


        //public async void PostAycn(string data)
        //{
        //    HttpClient client = new HttpClient();
        //    client.BaseAddress = new Uri("http://localhost/MedicalAdviser.RestService/AdviserOperations.svc");

        //    // Add an Accept header for JSON format.
        //    client.DefaultRequestHeaders.Accept.Add(
        //        new MediaTypeWithQualityHeaderValue("application/json"));

        //    var formatters = new List<MediaTypeFormatter>() {
        //        new JsonMediaTypeFormatter(),
        //        new XmlMediaTypeFormatter()
        //    };

        //    // Create a new product
        //    var gizmo = new Login() {  AccessToken = "Gizmo", Type = 100, App = "Widget" };
        //    Uri gizmoUri = null;
        //    String content;

        //    dts.ServiceOut<Login> ouOut;

        //    var response = client.PostAsJsonAsync("http://localhost/MedicalAdviser.RestService/AdviserOperations.svc/Account", gizmo).Result;

        //    //Exemplo de serialização do conteudo do objecto
        //    //StringContent cenaContent = new System.Net.Http.StringContent(gizmo.ToString(), Encoding.UTF8, "application/json");
        //    //var result = client.PutAsync("api/Values", cenaContent).Result;

        //    if (response.IsSuccessStatusCode)
        //    {
        //        gizmoUri = response.Headers.Location;

        //        //response.Content.ReadAsStringAsync().ContinueWith(
        //        //          (readTask) =>
        //        //              {
        //        //                  content = readTask.Result.ToString();
        //        //              });

               

        //       content =  response.Content.ReadAsStringAsync().Result.ToString();
        //       ouOut = JsnUtils.Json.JsonConvert.DeserializeObject<dts.ServiceOut<Login>>(content);
        //    }
        //    else
        //    {
        //        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        //    }

        //}



        //#region Make the HTTP operation like old fasion way

        //public async void MakePost(String url)
        //{


        //    Login user = new Login()
        //    {
        //        AccessToken = "12342",
        //        App = "MedicalAdvertising",
        //        Type = 23
        //    };

        //    ParametersConvert<Login> convert = new ParametersConvert<Login>();

        //    String str = convert.SerializeJsonToString(user);

        //    // Create a request using a URL that can receive a post. 
        //    WebRequest request = WebRequest.Create(url);
        //    // Set the Method property of the request to POST.
        //    request.Method = "POST";
        //    // Create POST data and convert it to a byte array.
        //    string postData = str;
        //    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        //    // Set the ContentType property of the WebRequest.
        //    request.ContentType = "application/json";
        //    // Set the ContentLength property of the WebRequest.
        //    request.ContentLength = byteArray.Length;
        //    // Get the request stream.
        //    Stream dataStream = request.GetRequestStream();
        //    // Write the data to the request stream.
        //    dataStream.Write(byteArray, 0, byteArray.Length);
        //    // Close the Stream object.
        //    dataStream.Close();
        //    // Get the response.
        //    WebResponse response = request.GetResponse();
        //    // Display the status.
        //    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        //    // Get the stream containing content returned by the server.
        //    dataStream = response.GetResponseStream();
        //    // Open the stream using a StreamReader for easy access.
        //    StreamReader reader = new StreamReader(dataStream);
        //    // Read the content.
        //    string responseFromServer = reader.ReadToEnd();
        //    // Display the content.
        //    Console.WriteLine(responseFromServer);
        //    // Clean up the streams.
        //    reader.Close();
        //    dataStream.Close();
        //    response.Close();
        //}


        //#endregion 

    }
}
